﻿using System;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Routing;

namespace Portal
{
    public class CultureAwareHttpModule : IHttpModule
    {
        private CultureInfo _currentCulture;
        private CultureInfo _currentUiCulture;
        public void Dispose() { }
        public void Init(HttpApplication context)
        {
            context.BeginRequest += SetCurrentCulture;
            context.EndRequest += RecoverCulture;
        }

        private void SetCurrentCulture(object sender, EventArgs args)
        {
            _currentCulture = Thread.CurrentThread.CurrentCulture;
            _currentUiCulture = Thread.CurrentThread.CurrentUICulture;
            HttpContextBase contextWrapper = new HttpContextWrapper(HttpContext.Current);
           RouteData routeData = RouteTable.Routes.GetRouteData(contextWrapper);
            object culture;
            if (routeData != null && routeData.Values.TryGetValue("culture", out culture))
            {

                try
                {
                    if (culture != null)
                    {
                        Thread.CurrentThread.CurrentCulture = new CultureInfo(culture.ToString());
                        Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture.ToString());
                    }

                }
                catch (Exception e)
                { throw new ArgumentException("Thread Is Error"); }
            }

        }
        private void RecoverCulture(object sender, EventArgs args)
        {
            Thread.CurrentThread.CurrentCulture = _currentCulture;
            Thread.CurrentThread.CurrentUICulture = _currentUiCulture;

        }
    }
}
